﻿using BCCommon;
using BCService.Common.WebsiteConfigurationService;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using WeChatSDK.Common;
using WeChatSDK.WeChatDto.Conversation.BaseSupport;
using WeChatSDK.WeChatServiceComponent.Conversation.BaseSupport;

namespace BCTMSRESTful.Controllers.Management.WeChat
{
    /// <summary>
    /// 微信JSAPI信息控制器
    /// </summary>
    [ApiExplorerSettings(GroupName = "Admin")]
    [Route("api/v1/sim/[controller]")]
    public class WeChatInfoController : ManagementBaseController
    {
        private readonly IWebsiteConfigurationService websiteConfigurationService;

        public WeChatInfoController(IWebsiteConfigurationService websiteConfigurationService)
        {
            this.websiteConfigurationService = websiteConfigurationService;
        }

        /// <summary>
        /// 获取微信JsapiTicket。
        /// </summary>
        /// <response code="200">AccessToken。</response>
        /// <returns></returns>
        [HttpGet("[action]")]
        public IActionResult JsapiTicket()
        {
            WeChatAccessTokenDto weChatAccessTokenDto  =  new BaseSupportService().CreateAccessToken();
            string nonceStr = RandomCode.GenerateUniqueCode(8);
            int timestamp = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("noncestr", nonceStr);
            keyValuePairs.Add("jsapi_ticket", weChatAccessTokenDto.JsapiTicket);
            keyValuePairs.Add("timestamp", timestamp);
            keyValuePairs.Add("url", this.websiteConfigurationService.Get(1).Host);
            string args = string.Join("&", keyValuePairs.OrderBy(p => p.Key).Select(d => string.Concat(d.Key, "=", d.Value)));
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] sign = sha1.ComputeHash(Encoding.UTF8.GetBytes(args));
            sha1.Clear();
            string output = BitConverter.ToString(sign);
            output = output.Replace("-", "");
            output = output.ToLower();
            object obj = new
            {
                JsapiTicket = weChatAccessTokenDto.JsapiTicket,
                AccessToken = weChatAccessTokenDto.AccessToken,
                AppId = WeChatInfo.AppId,
                Signature = output,
                NonceStr = nonceStr,
                Timestamp = timestamp
            };
            return this.Ok(obj);
        }
        
    }
}
